package at.jku.pervasive;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

public class UbisenseListener
{

	private List<PositionListener> positionListeners;

	public UbisenseListener()
	{
		super();
		this.positionListeners = new ArrayList<PositionListener>(1);
	}

	public void addPositionListener(PositionListener posListener)
	{
		this.positionListeners.add(posListener);
	}

	public void removePositionListener(PositionListener posListener)
	{
		this.positionListeners.remove(posListener);
	}

	private Socket clientSocket;

	public void startListening(final String host, final int port)
	{
		new Thread(new Runnable()
		{

			public void run()
			{
				try
				{
					clientSocket = new Socket(host, port);
					InputStream inputStream = clientSocket.getInputStream();
					BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

					String line;
					while ((line = reader.readLine()) != null)
					{
						Position pos = new Position(line);
						for (PositionListener posListener : UbisenseListener.this.positionListeners)
						{
							posListener.positionReceived(pos);
						}
					}
				} catch (UnknownHostException e)
				{
					e.printStackTrace();
				} catch (IOException e)
				{
					// silent
				}
			}
		}).start();
	}

	public void stopListening()
	{
		try
		{
			if (clientSocket != null)
				clientSocket.close();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}

}
